<template>
  <div class="joke-view">
    <BaseBox>
      <template #title>
        <span @click="$store.commit('addNumWith5')">{{
          $store.state.num
        }}</span>
        <p @click="$store.commit('addNumWithSome', 10)">
          {{ $store.state.num }}
        </p>
        <BaseTitle>开心一笑😁</BaseTitle>
      </template>
      <div class="content">
        <base-button type="success" @click="getJoke">获取新笑话</base-button>
        <p class="text">{{ joke }}</p>
      </div>
    </BaseBox>
  </div>
</template>

<script>
import { getJokeAPI } from '@/api'

export default {
  name: "JokeView",
  data() {
    return {
      joke: "",
      timerId: null
    };
  },

// 页面打开的钩子
  async created() {
    // 先默认请求一条数据
    this.getJoke()

    // 每隔8秒调用一下
    this.timerId = setInterval( () => {

      console.log('我调用了')
      this.getJoke()

    }, 1000 )
  },

  beforeDestroy() {

    // console.log('笑话组件销毁了')
    // 以后要记住：但凡在组件里开了定时器，一定要写一个销毁的钩子来把定时器关掉
    // 销毁有两个钩子，随便哪个都行，他们区别在于一个能访问子组件，一个不能访问子组件
    clearInterval(this.timerId)
  },

  methods: {
    async getJoke() {

      let res = await getJokeAPI()
      this.joke = res.data;
    },
  },
};
</script>

<style lang="less" scoped>
.joke-view {
  .time {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    .base-switch {
      margin-right: 5px;
    }
  }
  .text {
    font-size: 30px;
    color: #6a4d52;
    cursor: pointer;
  }
}
</style>
